#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangYlhskzzzrmzfPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_ylhskzzzrmzf_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "伊犁哈萨克自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['伊犁哈萨克自治州人民政府', "", "https://www.xjyl.gov.cn/xjylz/c112884/zfxxgk_gknrz.shtml"],
            ['伊犁哈萨克自治州人民政府', "", "https://www.xjyl.gov.cn/xjylz/c112883/zfxxgk_gfxwjk.shtml"],
            ['伊犁哈萨克自治州人民政府', "", "https://www.xjyl.gov.cn/xjylz/c112781/xxgk_list.shtml"],
            ['伊犁哈萨克自治州人民政府', "", "https://www.xjyl.gov.cn/xjylz/c112801/xxgk_list.shtml"],
            ['伊宁市人民政府', "伊宁市", "https://www.yining.gov.cn/yining/c116728/zfxxgklist.shtml"],
            ['奎屯市人民政府', "奎屯市", "https://www.xjkuitun.gov.cn/xjkuitun/c115974/zfxxgk_gknrz.shtml"],
            ['奎屯市人民政府', "奎屯市", "https://www.xjkuitun.gov.cn/xjkuitun/gkzcfg/list.shtml"],
            ['奎屯市人民政府', "奎屯市", "https://www.xjkuitun.gov.cn/xjkuitun/zfwj/list.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114462/zfxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114374/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114376/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114378/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114382/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114405/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114409/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114415/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114423/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114440/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114442/bmxxgklist.shtml"],
            ['霍尔果斯市人民政府', "霍尔果斯市", "http://www.xjhegs.gov.cn/xjhegs/c114447/bmxxgklist.shtml"],
            ['伊宁县人民政府', "伊宁县", "https://www.xjyn.gov.cn/xjyn/c118429/zfxxgk_gknrz.shtml"],
            ['霍城县人民政府', "霍城县", "https://www.xjhc.gov.cn/xjhc/c113362/zfxxgk_gknrz.shtml"],
            ['霍城县人民政府', "霍城县", "https://www.xjhc.gov.cn/xjhc/c116862/zfxxgk_gfxwjk.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115366/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115372/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115374/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115380/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115385/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115393/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115411/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115414/zfbm_list.shtml"],
            ['察布查尔锡伯自治县人民政府', "察布查尔县", "http://www.xjcbcr.gov.cn/xjcbcr/c115426/zfbm_list.shtml"],
            ['尼勒克县人民政府', "尼勒克县", "https://www.xjnlk.gov.cn/xjnlk/c113080/zfxxgk_gknrz.shtml"],
            ['巩留县人民政府', "巩留县", "https://www.xjgl.gov.cn/xjgl/c116021/zfxxgk_gknrz.shtml"],
            ['新源县人民政府', "新源县", "https://www.xinyuan.gov.cn/xinyuan/c116716/zfxxgk_gknrz.shtml"],
            ['新源县人民政府', "新源县", "https://www.xinyuan.gov.cn/xinyuan/c113900/common_list.shtml"],
            ['新源县人民政府', "新源县", "https://www.xinyuan.gov.cn/xinyuan/c113901/common_list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c114074/zfxxgk_list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c113820/list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c113825/list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c113826/list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c113830/list.shtml"],
            ['昭苏县人民政府', "昭苏县", "https://www.zhaosu.gov.cn/zsx/c113831/list.shtml"],
            ['特克斯县人民政府', "特克斯县", "http://www.zgtks.gov.cn/zgtks/zfwj/zfxxgk_xxgkzd.shtml"],
            ['特克斯县人民政府', "特克斯县", "http://www.zgtks.gov.cn/zgtks/tksxczj/list_zjlm.shtml"],
            ['特克斯县人民政府', "特克斯县", "http://www.zgtks.gov.cn/zgtks/tksxnyncj/list_zjlm.shtml"],
            ['特克斯县人民政府', "特克斯县", "http://www.zgtks.gov.cn/zgtks/tksxwhtygblyj/list_zjlm.shtml"],
            ['都拉塔管委会', "都拉塔", "http://www.zgdlt.gov.cn/zgdlt/c113595/list.shtml"],
            ['都拉塔管委会', "都拉塔", "http://www.zgdlt.gov.cn/zgdlt/c113601/list.shtml"],
            ['都拉塔管委会', "都拉塔", "http://www.zgdlt.gov.cn/zgdlt/c113602/list.shtml"],
            ['奎屯-独山子经济技术开发区', "奎屯-独山子经济技术开发区", "https://kdjkq.xinjiang.gov.cn/ktdsz/xxgkzcwj/zfxxgk_xxgkzd.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='table-main' or @class='table-responsive' or @class='govnewslista2353']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='table-main' or @class='zfxxgk_right']//dd//a[contains(@href, 'htm') or @title]/ancestor::dd[string-length(string(.))>=5] |"
                "//table/tr/td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='content' or @class='zfxxgk_right']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] |"
                "//div[@class]/ul[@class]//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            if 'list.shtml' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_ylhskzzzrmzf_policy".split())
